package com.shop.admin.controller;

import com.alibaba.fastjson.util.TypeUtils;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.admin.entity.Organization;
import com.shop.admin.entity.Rider;
import com.shop.admin.entity.ShopAdmin;
import com.shop.admin.entity.SysUserRole;
import com.shop.admin.interceptors.JWTInterceptor;
import com.shop.admin.result.ApiResult;
import com.shop.admin.service.*;
import com.shop.admin.utils.PageUtils;

import com.shop.admin.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Api(tags = {"SchoolAdminController"},description = "学校管理员接口")
@RestController
@RequestMapping("api/school/admin")
public class SchoolAdminController {

    @Resource
    private ShopAdminService shopAdminService;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private ShopCategoryService shopCategoryService;

    @Resource
    private ShopSlideshowService shopSlideshowService;

    @Resource
    private ShopOrderService shopOrderService;

    @Resource
    private ShopIndentService shopIndentService;

    @Resource
    private ShopGoodsService shopGoodsService;

    @Resource
    private AllOrderService allOrderService;

    @Resource
    private RiderService riderService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    //学校管理登录
    @PostMapping("/login")
    @ApiOperation(value = "学校管理登录",notes = "用户名和密码")
    public Object AdminLogin(@ApiParam("参数列表为+" +
            "{\n" +
            "    \"adminUser\":\"admin\",\n" +
            "    \"adminPassword\":\"admin404\"\n" +
            "}")@RequestBody Map<String, String> map) {
        return shopAdminService.schoolLogin(map);
    }

    //获取学校列表查询
//    @GetMapping("/school/list")
//    @ApiOperation(value = "获取学校列表查询",notes = "")
//    public ApiResult schoolList(@RequestParam Map<String, Object> params){
//        PageUtils page = organizationService.schoolList(params);
//        return ApiResult.ok(page);
//    }

    //获取学校列表查询
    @GetMapping("/school/map")
    @ApiOperation(value = "获取学校楼栋列表查询",notes = "")
    public ApiResult sonList(@RequestParam Map<String, Object> params){
        List<AdminMapVo> map = organizationService.sonSchoolList1(params);
        Long page = params.containsKey("page") ? Long.parseLong(params.get("page").toString()) : null;
        Long limit = params.containsKey("limit") ? Long.parseLong(params.get("limit").toString()) : null;
        if (page!=null&&limit!=null){
            Page<AdminMapVo> res = new Page<>(page, limit);
            //Page<AdminMapVo> page = new Page<AdminMapVo>(Long.parseLong(params.get("page").toString()),Long.parseLong(params.get("limit").toString()));
            res.setRecords(map);
            res.setTotal(map.size());
            PageUtils pageUtils=new PageUtils(res);
            return ApiResult.ok(pageUtils);
        }
       return ApiResult.ok(map);
    }

    //获取学校楼栋管理员列表
    @GetMapping("/school/admin/list")
    @ApiOperation(value = "获取学校楼栋管理员列表",notes = "楼栋id(orgId)")
    public ApiResult schoolAdminList(@RequestParam Map<String, Object> params){
        PageUtils page = shopAdminService.adminSchoolList(params);
        return ApiResult.ok(page);
    }

    //获取学校楼栋管理员列表
//    @GetMapping("/school/admin/list/stram")
// //   @ApiOperation(value = "获取学校楼栋管理员列表",notes = "楼栋id(orgId)")
//    public ApiResult schoolAdminListStream(@RequestParam Map<String, Object> params){
//        PageUtils page = shopAdminService.adminSchoolListStream(params);
//        return ApiResult.ok(page);
//    }

    @GetMapping("/data/list")
    @ApiOperation(value = "获取盈利，销售，订单总数量",notes = "传参组织id")
    public ApiResult dataList(@ApiParam("参数为：orgId") @RequestParam Map<String, Object> params){
        DataVo vos = shopIndentService.queryPageData(params);
        return ApiResult.ok(vos);
    }

    @GetMapping("/ranking")
    @ApiOperation(value = "获取销售排行榜",notes = "组织id(orgId)")
    public ApiResult ranking(@RequestParam Map<String, Object> params){
        List<RankingVo> vos = shopGoodsService.rankingList(params);
        return ApiResult.ok(vos);
    }

    //获取学校下的楼栋管理员模块列表查询
    @PostMapping("/school/data/list")
    @ApiOperation(value = "获取学校下次级楼栋管理员模块列表",notes = "传参：学校下楼栋id(orgId)")
    public ApiResult organizationAdmin(@ApiParam("参数:{\n" +
            "    \"orgId\":\"2\",\n" +
            "}")@RequestBody DataAdminVo vo){
        List<OrganizationAdminCountVo> vos = organizationService.getOrganizationAdminCount(vo);
        return ApiResult.ok(vos);
    }

    @GetMapping("/zation")
    @ApiOperation(value = "获取7天的销售,销售订单量",notes = "组织id(orgId)")
    public ApiResult imageization(@ApiParam("") @RequestParam Map<String, Object> params){
        Map<String, List<Object>> vos = shopIndentService.getImageIzation(params);
        return ApiResult.ok(vos);
    }

    /**
     * 跑腿订单列表
     */
    @GetMapping("/errand/list")
    @ApiOperation(value = "跑腿订单列表",notes = "page,limit,系统订单号，订单状态,发起用户姓名，发起用户手机号，接单用户姓名，接单用户手机，接单用户学号，组织id,价格低，价格高")
    public ApiResult errandList( @ApiParam("参数为：page,limit,orderCode,orderStatus,userNick,phoneNumber，name，riderPhone,studentNumber,orgId，priceBegin，priceEnd")@RequestParam Map<String, Object> params){
        PageUtils page = allOrderService.queryPage(params);
        return ApiResult.ok(page);
    }

    /**
     * 骑手列表
     */
    @GetMapping("/rider/list")
    @ApiOperation(value = "骑手列表",notes = "page,limit 条件查询，姓名，手机号，学号，组织id,状态")
    public ApiResult riderList( @ApiParam("参数为：page,limit,name，riderPhone,studentNumber,orgId,state")@RequestParam Map<String, Object> params){
        PageUtils page = riderService.queryPage(params);
        return ApiResult.ok(page);
    }

    /**
     * 学校组织新增或修改
     */
    @PostMapping("/org/save")
    @ApiOperation(value = "学校组织新增或修改",notes = "楼栋名称，抽成，配送费，wx支付抽成，父类id")
    public ApiResult orgSchoolSave(@ApiParam("参数为：orgName,commission，deliveryPrices，wx_rate(默认0.0060),fatherId") @RequestBody Organization organization){
        if (organizationService.selectBoolean(organization.getId(),organization.getOrgName(),organization.getFatherId())){
            organization.setSalesCommission(new BigDecimal(0));
            organizationService.saveOrUpdate(organization);
            return ApiResult.ok("操作成功");
        }
        return ApiResult.ok("数据重复，请修改数据");
    }

    /**
     * 组织管理员新增或修改
     */
    @PostMapping("/org/admin")
    @ApiOperation(value = "学校组织管理员新增或修改",notes = "管理员账户，密码后台默认为admin，姓名，邮箱,邮箱状态(0不接收 1 接收邮件)，组织id,角色id")
    public ApiResult orgAdminSave(@ApiParam("参数为：adminUser，adminName，adminMail,receiveEmail,orgId,roleId") @RequestBody AdminRoleVo admin, HttpServletRequest request) {
        String adminId =  JWTInterceptor.userId;
        ShopAdmin shopAdmin = new ShopAdmin();
        BeanUtils.copyProperties(admin,shopAdmin);
        if (admin.getId()!=null){
            //修改
            if (shopAdminService.selectBoolean(admin.getAdminUser(),admin.getId())) {
                shopAdmin.setCreateAdminId(Long.parseLong(adminId));
                shopAdmin.setUpdateTime(new Date());
                shopAdminService.updateById(shopAdmin);
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(admin.getRoleId());
                sysUserRole.setUpdateTime(new Date());
                sysUserRoleService.update(sysUserRole,new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,admin.getId()));
                return ApiResult.ok("修改成功");
            }
        }else {
            //新增
            if (shopAdminService.selectBoolean(admin.getAdminUser(),admin.getId())) {
                shopAdmin.setCreateAdminId(Long.parseLong(adminId));
                shopAdmin.setAdminPassword("admin");
                shopAdmin.setStatus(1);
                shopAdmin.setCreateTime(new Date());
                shopAdminService.save(shopAdmin);
                Long id = shopAdmin.getId();
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(admin.getRoleId());
                sysUserRole.setUserId(id.intValue());
                sysUserRole.setCreateTime(new Date());sysUserRole.setIsDeleted(0);
                sysUserRoleService.save(sysUserRole);
                return ApiResult.ok("新增成功");
            }
        }
        return ApiResult.ok("账号重复，请修改数据");
        }
}
